

import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import styles from './styles.module.css';
import { historyAPI } from '../../services/api';
import { getAuthToken } from '../../utils/auth';

interface HistoryRecord {
  id: string;
  date: string;
  food_name: string;
  portion: string;
  calories: number;
  protein: number;
  carb: number;
  fat: number;
  record_time: string;
}

type SortField = 'date' | 'food_name' | 'calories' | 'protein' | 'carb' | 'fat' | 'record_time';
type SortOrder = 'asc' | 'desc';

const HistoryPage: React.FC = () => {
  const navigate = useNavigate();
  


  // 状态管理
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(10);
  const [sortField, setSortField] = useState<SortField>('date');
  const [sortOrder, setSortOrder] = useState<SortOrder>('desc');
  const [filteredData, setFilteredData] = useState<HistoryRecord[]>([]);
  const [deleteRecordId, setDeleteRecordId] = useState<string | null>(null);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [searchInput, setSearchInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [totalRecords, setTotalRecords] = useState(0);

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '食算 - 历史记录';
    return () => { document.title = originalTitle; };
  }, []);

  // 初始化日期选择器
  useEffect(() => {
    const today = new Date();
    const startDate = new Date(today);
    startDate.setDate(today.getDate() - 30); // 默认显示最近30天
    
    setStartDate(startDate.toISOString().split('T')[0]);
    setEndDate(today.toISOString().split('T')[0]);
  }, []);

  // 加载历史记录数据
  useEffect(() => {
    loadHistoryData();
  }, [currentPage, startDate, endDate]);

  // 加载历史记录数据
  const loadHistoryData = async () => {
    const token = getAuthToken();
    if (!token) {
      setError('请先登录');
      return;
    }

    setLoading(true);
    try {
      const response = await historyAPI.getHistory(currentPage, pageSize);
      // 转换API数据格式为前端需要的格式
      const convertedRecords: HistoryRecord[] = response.records.map((record: any) => ({
        id: record.id.toString(),
        date: record.record_date,
        food_name: record.food_name,
        portion: `${record.portion_value}${record.portion_unit || 'g'}`,
        calories: Math.round(record.calories * (record.portion_value / 100)),
        protein: parseFloat((record.protein * (record.portion_value / 100)).toFixed(1)),
        carb: parseFloat((record.carb * (record.portion_value / 100)).toFixed(1)),
        fat: parseFloat((record.fat * (record.portion_value / 100)).toFixed(1)),
        record_time: new Date(record.created_at).toLocaleTimeString('zh-CN', { 
          hour: '2-digit', 
          minute: '2-digit' 
        })
      }));
      
      setFilteredData(convertedRecords);
      setTotalRecords(response.pagination.totalRecords);
    } catch (err) {
      setError('加载历史记录失败');
      console.error('Error loading history:', err);
    } finally {
      setLoading(false);
    }
  };

  // 过滤数据
  const filterData = () => {
    let filtered = [...filteredData];

    // 日期范围过滤
    if (startDate && endDate) {
      filtered = filtered.filter(record => {
        const recordDate = new Date(record.date);
        const start = new Date(startDate);
        const end = new Date(endDate);
        end.setHours(23, 59, 59, 999); // 包含结束日期的全天
        
        return recordDate >= start && recordDate <= end;
      });
    }

    // 搜索过滤
    if (searchInput.trim()) {
      const searchTerm = searchInput.toLowerCase();
      filtered = filtered.filter(record => 
        record.food_name.toLowerCase().includes(searchTerm)
      );
    }

    return filtered;
  };

  // 排序数据
  const sortData = (data: HistoryRecord[]) => {
    const sorted = [...data].sort((a, b) => {
      let aValue: any = a[sortField];
      let bValue: any = b[sortField];

      if (sortField === 'date') {
        aValue = new Date(aValue);
        bValue = new Date(bValue);
      }

      if (sortOrder === 'asc') {
        return aValue > bValue ? 1 : -1;
      } else {
        return aValue < bValue ? 1 : -1;
      }
    });

    return sorted;
  };

  // 处理排序
  const handleSort = (field: SortField) => {
    const newSortOrder = sortField === field ? (sortOrder === 'asc' ? 'desc' : 'asc') : 'asc';
    setSortField(field);
    setSortOrder(newSortOrder);
    sortData(filteredData);
  };

  // 处理分页
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  // 编辑记录
  const editRecord = (recordId: string) => {
    navigate(`/food-detail?recordId=${recordId}`);
  };

  // 显示删除确认对话框
  const showDeleteConfirmation = (recordId: string) => {
    setDeleteRecordId(recordId);
    setShowDeleteModal(true);
  };

  // 隐藏删除确认对话框
  const hideDeleteModal = () => {
    setShowDeleteModal(false);
    setDeleteRecordId(null);
  };

  // 删除记录
  const deleteRecord = async (recordId: string) => {
    try {
      await historyAPI.deleteRecord(recordId);
      // 重新加载数据
      loadHistoryData();
    } catch (err) {
      setError('删除记录失败');
      console.error('Error deleting record:', err);
    } finally {
      hideDeleteModal();
    }
  };

  // 格式化日期
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    });
  };

  // 处理搜索框回车
  const handleSearchKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      navigate('/food-search');
    }
  };

  // 计算分页数据
  const filteredAndSortedData = sortData(filterData());
  const startIndex = (currentPage - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const currentData = filteredAndSortedData.slice(startIndex, endIndex);
  const totalItems = filteredAndSortedData.length;
  const calculatedTotalPages = Math.ceil(totalItems / pageSize);
  const startItem = totalItems > 0 ? startIndex + 1 : 0;
  const endItem = Math.min(endIndex, totalItems);

  // 生成页码按钮
  const generatePageNumbers = () => {
    const maxVisiblePages = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

    if (endPage - startPage + 1 < maxVisiblePages) {
      startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    const pages = [];
    for (let i = startPage; i <= endPage; i++) {
      pages.push(i);
    }
    return pages;
  };

  return (
    <div className={styles.pageWrapper}>
      {/* 顶部导航栏 */}
      <header className="fixed top-0 left-0 right-0 bg-white border-b border-border-light h-16 z-50">
        <div className="flex items-center justify-between h-full px-6">
          {/* Logo和产品名称 */}
          <div className="flex items-center space-x-3">
            <div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
              <i className="fas fa-utensils text-white text-sm"></i>
            </div>
            <h1 className="text-xl font-bold text-text-primary">食算</h1>
          </div>
          
          {/* 全局搜索框 */}
          <div className="flex-1 max-w-md mx-8">
            <div className="relative">
              <input 
                type="text" 
                placeholder="搜索食物..." 
                value={searchInput}
                onChange={(e) => setSearchInput(e.target.value)}
                onKeyPress={handleSearchKeyPress}
                className="w-full pl-10 pr-4 py-2 border border-border-light rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              />
              <i className="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-text-secondary"></i>
            </div>
          </div>
          
          {/* 右侧操作区 */}
          <div className="flex items-center space-x-4">
            {/* 消息通知 */}
            <button className="relative p-2 text-text-secondary hover:text-primary">
              <i className="fas fa-bell text-lg"></i>
              <span className="absolute -top-1 -right-1 w-3 h-3 bg-danger rounded-full"></span>
            </button>
            
            {/* 用户头像和下拉菜单 */}
            <div className="relative">
              <button className="flex items-center space-x-2 p-1 rounded-lg hover:bg-gray-100">
                <img 
                  src="https://s.coze.cn/image/j0hrfZN2Ch0/" 
                  alt="用户头像" 
                  className="w-8 h-8 rounded-full" 
                />
                <span className="text-sm text-text-primary">张三</span>
                <i className="fas fa-chevron-down text-xs text-text-secondary"></i>
              </button>
            </div>
          </div>
        </div>
      </header>

      {/* 左侧菜单 */}
      <aside className={`fixed left-0 top-16 bottom-0 w-60 bg-white border-r border-border-light z-40 ${styles.sidebarTransition}`}>
        <nav className="p-4">
          <ul className="space-y-2">
            <li>
              <Link to="/home" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-home text-lg"></i>
                <span className="font-medium">首页</span>
              </Link>
            </li>
            <li>
              <Link to="/food-search" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-search text-lg"></i>
                <span className="font-medium">食物搜索</span>
              </Link>
            </li>
            <li>
              <Link to="/record-list" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-list text-lg"></i>
                <span className="font-medium">饮食记录</span>
              </Link>
            </li>
            <li>
              <Link to="/history" className={`${styles.navItem} ${styles.navItemActive} flex items-center space-x-3 px-4 py-3 rounded-lg`}>
                <i className="fas fa-history text-lg"></i>
                <span className="font-medium">历史记录</span>
              </Link>
            </li>
            <li>
              <Link to="/settings" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-cog text-lg"></i>
                <span className="font-medium">设置</span>
              </Link>
            </li>
          </ul>
        </nav>
      </aside>

      {/* 主内容区 */}
      <main className="ml-60 mt-16 p-6 min-h-screen">
        {/* 页面头部 */}
        <div className="flex items-center justify-between mb-8">
          <div>
            <h2 className="text-2xl font-bold text-text-primary">历史记录</h2>
            <nav className="flex items-center space-x-2 text-sm text-text-secondary mt-1">
              <span>历史记录</span>
            </nav>
          </div>
        </div>

        {/* 日期选择器区域 */}
        <section className="bg-white rounded-2xl shadow-card p-6 mb-8">
          <h3 className="text-lg font-semibold text-text-primary mb-4">选择日期范围</h3>
          <div className="flex flex-col md:flex-row gap-4">
            <div className="flex-1">
              <label htmlFor="start-date" className="block text-sm font-medium text-text-secondary mb-2">开始日期</label>
              <input 
                type="date" 
                id="start-date"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
                className="w-full px-4 py-2 border border-border-light rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              />
            </div>
            <div className="flex-1">
              <label htmlFor="end-date" className="block text-sm font-medium text-text-secondary mb-2">结束日期</label>
              <input 
                type="date" 
                id="end-date"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
                className="w-full px-4 py-2 border border-border-light rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              />
            </div>
            <div className="flex items-end">
              <button 
                onClick={filterData}
                className="bg-primary text-white px-6 py-2 rounded-lg hover:bg-indigo-600 transition-colors"
              >
                <i className="fas fa-search mr-2"></i>搜索
              </button>
            </div>
          </div>
        </section>

        {/* 历史记录表格 */}
        <section className="bg-white rounded-2xl shadow-card p-6 mb-8">
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-lg font-semibold text-text-primary">历史记录列表</h3>
            <div className="text-sm text-text-secondary">
              共 <span>{totalItems}</span> 条记录
            </div>
          </div>

          {/* 错误提示 */}
          {error && (
            <div className="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg">
              <div className="flex items-center justify-between">
                <div className="flex items-center">
                  <i className="fas fa-exclamation-circle text-red-500 mr-2"></i>
                  <span className="text-red-700">{error}</span>
                </div>
                <button 
                  onClick={() => setError(null)}
                  className="text-red-500 hover:text-red-700"
                >
                  <i className="fas fa-times"></i>
                </button>
              </div>
            </div>
          )}

          {/* 加载状态 */}
          {loading && (
            <div className="mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg text-center">
              <i className="fas fa-spinner fa-spin text-blue-500 mr-2"></i>
              <span className="text-blue-700">加载中...</span>
            </div>
          )}
          
          {/* 表格容器 */}
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-border-light">
                  <th 
                    className={`${styles.sortableHeader} text-left py-3 px-4 font-medium text-text-secondary`}
                    onClick={() => handleSort('date')}
                  >
                    日期
                    <i className={`fas ${sortField === 'date' ? (sortOrder === 'asc' ? 'fa-sort-up' : 'fa-sort-down') : 'fa-sort'} ml-1 text-xs`}></i>
                  </th>
                  <th 
                    className={`${styles.sortableHeader} text-left py-3 px-4 font-medium text-text-secondary`}
                    onClick={() => handleSort('food_name')}
                  >
                    食物名称
                    <i className={`fas ${sortField === 'food_name' ? (sortOrder === 'asc' ? 'fa-sort-up' : 'fa-sort-down') : 'fa-sort'} ml-1 text-xs`}></i>
                  </th>
                  <th className="text-left py-3 px-4 font-medium text-text-secondary">份量</th>
                  <th 
                    className={`${styles.sortableHeader} text-left py-3 px-4 font-medium text-text-secondary`}
                    onClick={() => handleSort('calories')}
                  >
                    卡路里
                    <i className={`fas ${sortField === 'calories' ? (sortOrder === 'asc' ? 'fa-sort-up' : 'fa-sort-down') : 'fa-sort'} ml-1 text-xs`}></i>
                  </th>
                  <th 
                    className={`${styles.sortableHeader} text-left py-3 px-4 font-medium text-text-secondary`}
                    onClick={() => handleSort('protein')}
                  >
                    蛋白质(g)
                    <i className={`fas ${sortField === 'protein' ? (sortOrder === 'asc' ? 'fa-sort-up' : 'fa-sort-down') : 'fa-sort'} ml-1 text-xs`}></i>
                  </th>
                  <th 
                    className={`${styles.sortableHeader} text-left py-3 px-4 font-medium text-text-secondary`}
                    onClick={() => handleSort('carb')}
                  >
                    碳水(g)
                    <i className={`fas ${sortField === 'carb' ? (sortOrder === 'asc' ? 'fa-sort-up' : 'fa-sort-down') : 'fa-sort'} ml-1 text-xs`}></i>
                  </th>
                  <th 
                    className={`${styles.sortableHeader} text-left py-3 px-4 font-medium text-text-secondary`}
                    onClick={() => handleSort('fat')}
                  >
                    脂肪(g)
                    <i className={`fas ${sortField === 'fat' ? (sortOrder === 'asc' ? 'fa-sort-up' : 'fa-sort-down') : 'fa-sort'} ml-1 text-xs`}></i>
                  </th>
                  <th 
                    className={`${styles.sortableHeader} text-left py-3 px-4 font-medium text-text-secondary`}
                    onClick={() => handleSort('record_time')}
                  >
                    记录时间
                    <i className={`fas ${sortField === 'record_time' ? (sortOrder === 'asc' ? 'fa-sort-up' : 'fa-sort-down') : 'fa-sort'} ml-1 text-xs`}></i>
                  </th>
                  <th className="text-left py-3 px-4 font-medium text-text-secondary">操作</th>
                </tr>
              </thead>
              <tbody>
                {currentData.map(record => (
                  <tr key={record.id} className={`${styles.tableRow} border-b border-border-light`}>
                    <td className="py-3 px-4 text-text-primary">{formatDate(record.date)}</td>
                    <td className="py-3 px-4 text-text-primary">{record.food_name}</td>
                    <td className="py-3 px-4 text-text-secondary">{record.portion}</td>
                    <td className="py-3 px-4 text-text-primary font-medium">{record.calories}</td>
                    <td className="py-3 px-4 text-text-secondary">{record.protein.toFixed(1)}</td>
                    <td className="py-3 px-4 text-text-secondary">{record.carb.toFixed(1)}</td>
                    <td className="py-3 px-4 text-text-secondary">{record.fat.toFixed(1)}</td>
                    <td className="py-3 px-4 text-text-secondary">{record.record_time}</td>
                    <td className="py-3 px-4">
                      <div className="flex space-x-2">
                        <button 
                          onClick={() => editRecord(record.id)}
                          className="text-primary hover:text-indigo-600 text-sm"
                        >
                          <i className="fas fa-edit mr-1"></i>编辑
                        </button>
                        <button 
                          onClick={() => showDeleteConfirmation(record.id)}
                          className="text-danger hover:text-red-600 text-sm"
                        >
                          <i className="fas fa-trash mr-1"></i>删除
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          
          {/* 分页控件 */}
          <div className="flex items-center justify-between mt-6 pt-6 border-t border-border-light">
            <div className="text-sm text-text-secondary">
              显示第 <span>{startItem}</span> - <span>{endItem}</span> 条，共 <span>{totalItems}</span> 条
            </div>
            <div className="flex items-center space-x-2">
              <button 
                onClick={() => handlePageChange(currentPage - 1)}
                disabled={currentPage <= 1}
                className={`${styles.paginationBtn} px-3 py-1 border border-border-light rounded ${currentPage <= 1 ? styles.disabled : ''}`}
              >
                <i className="fas fa-chevron-left"></i>
              </button>
              <div className="flex items-center space-x-1">
                {generatePageNumbers().map(pageNum => (
                  <button 
                    key={pageNum}
                    onClick={() => handlePageChange(pageNum)}
                    className={`${styles.paginationBtn} px-3 py-1 border border-border-light rounded ${pageNum === currentPage ? styles.active : ''}`}
                  >
                    {pageNum}
                  </button>
                ))}
              </div>
              <button 
                onClick={() => handlePageChange(currentPage + 1)}
                disabled={currentPage >= calculatedTotalPages}
                className={`${styles.paginationBtn} px-3 py-1 border border-border-light rounded ${currentPage >= calculatedTotalPages ? styles.disabled : ''}`}
              >
                <i className="fas fa-chevron-right"></i>
              </button>
            </div>
          </div>
        </section>
      </main>

      {/* 删除确认对话框 */}
      {showDeleteModal && (
        <div 
          className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center"
          onClick={(e) => {
            if (e.target === e.currentTarget) {
              hideDeleteModal();
            }
          }}
        >
          <div className="bg-white rounded-2xl p-6 max-w-md w-full mx-4">
            <div className="text-center">
              <div className="w-16 h-16 bg-danger bg-opacity-10 rounded-full flex items-center justify-center mx-auto mb-4">
                <i className="fas fa-trash text-danger text-2xl"></i>
              </div>
              <h3 className="text-lg font-semibold text-text-primary mb-2">确认删除</h3>
              <p className="text-text-secondary mb-6">确定要删除这条饮食记录吗？此操作无法撤销。</p>
              <div className="flex space-x-3">
                <button 
                  onClick={hideDeleteModal}
                  className="flex-1 px-4 py-2 border border-border-light rounded-lg text-text-secondary hover:bg-gray-50"
                >
                  取消
                </button>
                <button 
                  onClick={() => deleteRecordId && deleteRecord(deleteRecordId)}
                  className="flex-1 px-4 py-2 bg-danger text-white rounded-lg hover:bg-red-600"
                >
                  删除
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default HistoryPage;

